package com.example.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author LEI
 * Created by LEI on 2020/3/19.
 */
public class FileUtils {
    /**
     * 递归获取某路径下的所有文件名 返回列表
     */
    public static List<String> getFileNames(String path) {
        List<String> fileNames = new ArrayList<String>();
        File file = new File(path);
        // 如果这个路径是文件夹
        if (file.isDirectory()) {
        // 获取路径下的所有文件
        File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if(files[i].isFile()){
                    String fileName = files[i].getName();
                    fileNames.add(fileName);
                }
            }
        }
        return fileNames;
    }

    /**将文件写入到本地磁盘
     * @param saveFile
     * @param input
     * @throws Exception
     */
    public static void writeToLocal(File saveFile, InputStream input) throws Exception{
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream downloadFile = new FileOutputStream(saveFile);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        downloadFile.close();
        input.close();
    }

    /**将二进制写入到本地磁盘
     *
     * @param saveFile 保存的位置
     * @param bytes 字节流
     * @throws IOException
     */
    public static void writeToLocal2(File saveFile, byte [] bytes) throws IOException {
        FileOutputStream downloadFile = new FileOutputStream(saveFile);
        downloadFile.write(bytes, 0, bytes.length);
        downloadFile.flush();
        downloadFile.close();
    }


    /**复制文件
     * @param source 源文件
     * @param dest 新文件
     */
    public static void copyFile(File source, File dest){
        InputStream input = null;
        OutputStream output = null;
        try {
            if(!source.exists()){
                return;
            }
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, bytesRead);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(input != null){input.close();}
                if(output != null){output.close();}
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
